package com.nwpu.coursesupport.realm;

import java.util.Collection;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.nwpu.coursesupport.entity.Assistant;
import com.nwpu.coursesupport.entity.bean.Setting;
import com.nwpu.coursesupport.service.imple.AssistantService;

public class AssistantAuthorizingRealm extends AuthorizingRealm {

    private static Logger logger = LoggerFactory.getLogger(StudentAuthorizingRealm.class);
	@Autowired
	private AssistantService assistantService;
	@Autowired
	private Setting setting;
	
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		Collection list=principals.fromRealm(this.getName());
		if(list==null||list.size()<=0){
			return null;
		}
        SimpleAuthorizationInfo simpleAuthorInfo = new SimpleAuthorizationInfo(); 
        simpleAuthorInfo.addRole("assistant"); 
        return simpleAuthorInfo;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
		try{
			CustomizedToken token = (CustomizedToken)authcToken;  
	        Assistant assistant = assistantService.findByAssistantCode(token.getUsername());  
	        if(assistant == null){
	        	return null;
	        }
	        token.setId(assistant.getId());
	        token.setName(assistant.getName());
	        token.setImage(assistant.getPicture());
	        ByteSource credentialsSalt = ByteSource.Util.bytes(assistant.getAssistantCode());
	        AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(assistant.getAssistantCode(),assistant.getPassword(),credentialsSalt, this.getName());  
	        return authcInfo;  
		}catch(Exception e){
			logger.error("助教登录出现问题："+e.getMessage());
		}
		return null;
	}
}
